package com.tcwlkj.uuService.ui.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.makeramen.roundedimageview.RoundedImageView;
import com.tcwlkj.uuService.MyApp;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.ImageUrlModel;
import com.tcwlkj.uuService.model.cityIDModel;
import com.tcwlkj.uuService.ui.BaseActivity;
import com.tcwlkj.uuService.utils.BitmapHelper;
import com.tcwlkj.uuService.utils.ChcheUtils;
import com.tcwlkj.uuService.utils.EventCenter;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.ToastUtil;
import com.tcwlkj.uuService.utils.Tools;
import com.yongchun.library.view.ImageSelectorActivity;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * Created by Administrator on 2017/10/17 0017.
 */

public class IDcertification extends BaseActivity implements TextWatcher {
    @Bind(R.id.et_city)
    EditText et_city;
    @Bind(R.id.et_name)
    EditText et_name;
    @Bind(R.id.et_id)
    EditText et_id;
    @Bind(R.id.et_jinji)
    EditText et_jinji;
    @Bind(R.id.img_head_idcheck)
    RoundedImageView roundedImageView;
    @Bind(R.id.iv_ID01)
    ImageView iv_ID01;
    @Bind(R.id.iv_ID02)
    ImageView iv_ID02;
    @Bind(R.id.iv_ID03)
    ImageView iv_ID03;
    @Bind(R.id.bt_regist)
    TextView bt_regist;
    private Intent intent;
    private static final String fileName = "TongchengImage.jpg";
    private Uri uri;
    private String mHead;
    private String mID01;
    private String mID02;
    private String mID03;
    private long mcityID;
    private CommonResponse<ImageUrlModel> imageUrlModel;
    String url0;
    String url1;
    String url2;
    String url3;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_id_check);
        ButterKnife.bind(this);
        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initview();
    }

    private void initview() {
        changeTitle("跑男身份验证");
        bt_regist.setBackgroundResource(R.drawable.bg_btn_id_gray);
        bt_regist.setClickable(false);
        et_city.addTextChangedListener(this);
        et_name.addTextChangedListener(this);
        et_id.addTextChangedListener(this);
        et_jinji.addTextChangedListener(this);
        et_name.setText(ChcheUtils.getInstance().getDriverDetailModel().getBase().getRealName());
        et_id.setText(ChcheUtils.getInstance().getDriverDetailModel().getBase().getIDNumber());
        et_jinji.setText(ChcheUtils.getInstance().getDriverDetailModel().getBase().getLinkNum());
        //getCity();
    }

    @OnClick({R.id.img_head_idcheck, R.id.iv_ID01, R.id.iv_ID02, R.id.iv_ID03, R.id.bt_regist})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_head_idcheck:
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        ActionSheetDialog(0, 1);
                    }
                }, R.string.CAMERA, Manifest.permission.CAMERA);
                break;
            case R.id.iv_ID01:
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        ActionSheetDialog(10, 11);
                    }
                }, R.string.CAMERA, Manifest.permission.CAMERA);
                break;
            case R.id.iv_ID02:
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        ActionSheetDialog(20, 21);
                    }
                }, R.string.CAMERA, Manifest.permission.CAMERA);
                break;
            case R.id.iv_ID03:
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        ActionSheetDialog(30, 31);
                    }
                }, R.string.CAMERA, Manifest.permission.CAMERA);
                break;
            case R.id.bt_regist:
                uploadID();
                break;
        }
    }

    private void uploadID() {
        String name = et_name.getText().toString().trim();
        String city = et_city.getText().toString().trim();
        String id = et_id.getText().toString().trim();
        String jinji = et_jinji.getText().toString().trim();
        try {
            if (!Tools.IDCardValidate(id)){
                ToastUtil.getInstance().show("请输入有效身份证号码");
                return;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(TextUtils.isEmpty(city)){
            ToastUtil.getInstance().show("当前城市不能为空");
            return;
        }
        if(!Tools.isMobileNumber(jinji)){
            ToastUtil.getInstance().show("手机号格式不正确");
            return;
        }
        if(jinji.equals(ChcheUtils.getInstance().getDriverDetailModel().getBase().getMobile())){
            ToastUtil.getInstance().show("紧急联系人号码不能为本人号码");
            return;
        }
        if (TextUtils.isEmpty(mHead)){
            ToastUtil.getInstance().show("请上传本人头像");
            return;
        }
        if(TextUtils.isEmpty(mID01)){
            ToastUtil.getInstance().show("请上传手持证件照");
            return;
        }
        if(TextUtils.isEmpty(mID02)){
            ToastUtil.getInstance().show("请上传身份证正面照");
            return;
        }
        if(TextUtils.isEmpty(mID03)){
            ToastUtil.getInstance().show("请上传身份证反面照");
            return;
        }
        Call<CommonResponse> httpResultCall=RetrofitUtils.getRequest(this,true).uploadID(PreferencesUtils.getString(MyApp.getContext(), "userID"),"",name,id,"1",jinji,url0,url1,url2,url3);
        httpResultCall.enqueue(new HttpCallBack<CommonResponse>() {
            @Override
            public void onSuccess(Object t) {
                ToastUtil.getInstance().show("跑男身份验证成功");
                PreferencesUtils.putString(MyApp.getContext(),"headImage",url0);
                EventBus.getDefault().post( new EventCenter<String>(50,""));
                finish();
            }
            @Override
            public void onFail(int code, String message) {
                if(code == 40104){
                    uploadID();
                }else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {//拍照
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        uri = Tools.getImageContentUri(baseContext, new File(Environment.getExternalStorageDirectory(), "/" + fileName));
                        cutImage(uri, 2);
                    }
                }, R.string.sd, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            } else if (requestCode == 0) {//从相册选取
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        uri = Tools.getImageContentUri(baseContext, new File(BitmapHelper.getImageAbsolutePath(baseContext, data.getData())));
                        cutImage(uri, 2);
                    }
                }, R.string.sd, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            } else if (requestCode == 11) {//拍照
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        uri = Tools.getImageContentUri(baseContext, new File(Environment.getExternalStorageDirectory(), "/" + fileName));
                        cutImage(uri, 12);
                    }
                }, R.string.sd, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            } else if (requestCode == 10) {//从相册选取
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        uri = Tools.getImageContentUri(baseContext, new File(BitmapHelper.getImageAbsolutePath(baseContext, data.getData())));
                        cutImage(uri, 12);
                    }
                }, R.string.sd, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            } else if (requestCode == 21) {//拍照
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        uri = Tools.getImageContentUri(baseContext, new File(Environment.getExternalStorageDirectory(), "/" + fileName));
                        cutImage(uri, 22);
                    }
                }, R.string.sd, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            } else if (requestCode == 20) {//从相册选取
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        uri = Tools.getImageContentUri(baseContext, new File(BitmapHelper.getImageAbsolutePath(baseContext, data.getData())));
                        cutImage(uri, 22);
                    }
                }, R.string.sd, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            } else if (requestCode == 31) {//拍照
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        uri = Tools.getImageContentUri(baseContext, new File(Environment.getExternalStorageDirectory(), "/" + fileName));
                        cutImage(uri, 32);
                    }
                }, R.string.sd, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            } else if (requestCode == 30) {//从相册选取
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        uri = Tools.getImageContentUri(baseContext, new File(BitmapHelper.getImageAbsolutePath(baseContext, data.getData())));
                        cutImage(uri, 32);
                    }
                }, R.string.sd, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            } else if (requestCode == 2) {//头像
                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(baseContext.getContentResolver(), Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "/cutphone")));
                    mHead=Tools.bitmapToBase64(bitmap);
                    uploadImage(mHead,0,"头像");
                    Bitmap bitmap1 = Tools.toRoundBitmap(bitmap);
                    roundedImageView.setImageBitmap(bitmap1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 12) {//证件
                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(baseContext.getContentResolver(), Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "/cutphone")));
                    //Bitmap bitmap1 = Tools.toRoundBitmap(bitmap);
                    mID01=Tools.bitmapToBase64(bitmap);
                    uploadImage(mID01,1,"证件");
                    iv_ID01.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 22) {//证件
                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(baseContext.getContentResolver(), Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "/cutphone")));
                    //Bitmap bitmap1 = Tools.toRoundBitmap(bitmap);
                    mID02=Tools.bitmapToBase64(bitmap);
                    uploadImage(mID02,2,"证件");
                    iv_ID02.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 32) {//证件
                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(baseContext.getContentResolver(), Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "/cutphone")));
                    //Bitmap bitmap1 = Tools.toRoundBitmap(bitmap);
                    mID03=Tools.bitmapToBase64(bitmap);
                    uploadImage(mID03,3,"证件");
                    iv_ID03.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private void uploadImage(String image,int type,String note) {
        Call<CommonResponse<ImageUrlModel>> httpResultCall = RetrofitUtils.getUploadRequest(this, true).upload("03A79706EC26C73C53018911BD88BC2842DE90808FDCC97E,"+type+"," + PreferencesUtils.getString(MyApp.getContext(), "userID") + ",3,0,"+note
                , image, "touxiang.jpg");
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<ImageUrlModel>>() {
            @Override
            public void onSuccess(Object t) {
                ToastUtil.getInstance().show("上传成功");
                switch (type){
                    case 0:
                        imageUrlModel = (CommonResponse<ImageUrlModel>) t;
                        url0= imageUrlModel.getData().getServer()+ imageUrlModel.getData().getUrl();
                        break;
                    case 1:
                        imageUrlModel= (CommonResponse<ImageUrlModel>) t;
                        url1= imageUrlModel.getData().getServer()+ imageUrlModel.getData().getUrl();
                        break;
                    case 2:
                        imageUrlModel= (CommonResponse<ImageUrlModel>) t;
                        url2= imageUrlModel.getData().getServer()+ imageUrlModel.getData().getUrl();
                        break;
                    case 3:
                        imageUrlModel= (CommonResponse<ImageUrlModel>) t;
                        url3= imageUrlModel.getData().getServer()+ imageUrlModel.getData().getUrl();
                        break;
                }
            }
            @Override
            public void onFail(int code, String message) {
                if(code == 40104){
                    ToastUtil.getInstance().show("请重新提交");
                }else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }

    /**
     * 拍照，相册弹出框
     */
    private void ActionSheetDialog(int pictureType, int cameraType) {
        final String[] stringItems = {"拍照", "从手机相册中选择"};
        final ActionSheetDialog dialog = new ActionSheetDialog(baseContext, stringItems, null);
        dialog.itemTextColor(Color.parseColor("#000000"))
                .itemTextSize(14.5f)
                .cancelText(Color.parseColor("#000000"))
                .cancelTextSize(14.5f)
                .show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 1: // 选择本地照片
                        intent = new Intent(Intent.ACTION_PICK);//标识选择数据me
                        intent.setType("image/*");//标识选择图片me
                        // 第二个参数为请求吗
                        startActivityForResult(intent, pictureType);
                        break;
                    case 0: // 拍照
                        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        if (Tools.isExistSd()) {
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), fileName)));
                            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                            StrictMode.setVmPolicy(builder.build());
                            builder.detectFileUriExposure();
                        }
                        startActivityForResult(intent, cameraType);
                        break;
                }
                dialog.dismiss();
            }
        });
    }

    /**
     * 定义方法裁剪图片
     */
    public void cutImage(Uri uri, int type) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1.5);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 512);//剪裁后X的像素
        intent.putExtra("outputY", 512);//剪裁后Y的像素
        intent.putExtra("output", Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "/cutphone"))); //保存路径me
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, type);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String name = et_name.getText().toString().trim();
        String city = et_city.getText().toString().trim();
        String id = et_id.getText().toString().trim();
        String jinji = et_jinji.getText().toString().trim();
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(id) && !TextUtils.isEmpty(jinji) && !TextUtils.isEmpty(city)) {
            bt_regist.setClickable(true);
            bt_regist.setBackgroundResource(R.drawable.bg_btn_id_org);
        } else {
            bt_regist.setClickable(false);
            bt_regist.setBackgroundResource(R.drawable.bg_btn_id_gray);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    public void getCity() {
        Call<CommonResponse<List<cityIDModel>>> httpResultCall = RetrofitUtils.getRequest(this, true).getCity("city");
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<List<cityIDModel>>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<List<cityIDModel>> commonResponse= (CommonResponse<List<cityIDModel>>) t;

                for(int i=0;i<commonResponse.getData().size();i++){
                    if(et_city.getText().toString().trim().equals(commonResponse.getData().get(i).getSName())){
                        mcityID=commonResponse.getData().get(i).getID();
                    }
                }
            }
            @Override
            public void onFail(int code, String message) {
                if(code == 40104){
                    getCity();
                }else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
